import { getAllPermission } from '@/api/permission'
let tempData = null
let maxTreeLength = 0

export function getPermissionTree(flush = false, expands = 2) {
  return new Promise(function(resolve, reject) {
    if (flush || tempData === null) {
      getAllPermission().then((res) => {
        const data = res.data
        handle(data)
        tempData = data
      })
    } else {
      handle(tempData)
    }

    function handle(data) {
      data.sort((a, b) => {
        return a.pid - b.pid
      })
      const temObj = {}
      let nowPid, nowId
      for (let i = data.length - 1; i >= 0; --i) {
        nowPid = data[i].pid
        nowId = data[i].id
        if (!temObj[nowPid]) temObj[nowPid] = []
        data[i].dataStatus = !!data[i].dataStatus
        temObj[nowPid].push(data[i])
        if (temObj[nowId]) {
          temObj[nowId].sort((a, b) => {
            return b.weight - a.weight
          })
          data[i].children = temObj[nowId]
          delete temObj[nowId]
        }
      }
      if (temObj[0][0].children) {
        const trees = [temObj[0][0]]
        const ids1 = recursion(trees, 0, expands)
        recursionDataMaxLength(trees, 0)
        resolve({ trees: trees, expands: ids1, maxLength: maxTreeLength - 1 })
      }
    }
  })
}

function recursionDataMaxLength(data, step) {
  ++step
  for (let i = 0; i < data.length; i++) {
    if (data[i].children instanceof Array) {
      recursionDataMaxLength(data[i].children, step)
    }
  }
  if (step > maxTreeLength) {
    maxTreeLength = step
  }
}

function recursion(data, step, expands) {
  let ids = []
  let item
  ++step
  for (let i = 0; i < data.length; i++) {
    item = data[i]
    ids.push(item.id)
    if (item.children && step < expands) {
      ids = ids.concat(recursion(item.children, step, expands))
    }
  }
  return ids
}
